import window from '../ui/web/window';

do { window::mount Root };

type Todo {
    content:  String,
    finished: Bool
};

function SmallButton:
    &(String,Async) => ui::Component
    &(args) => ({ ui::Button args } with { ui::Style ['min-width-2'] });

const Root: ui::Component :=
    let center := { ui::StyledContainer ['center'] },
    let row := { ui::StyledContainer ['row'] },
    \ list := use { ui::State { FlexList::[Todo] () } },
    let add-item-from: &(Reactive[String]) => Sync :=
        &(buffer) =>
            \ content := sync buffer.{->},
            \ id := sync { gen-monotonic-id-string () },
            \ sync (list append (id, { content, finished: No })),
            (buffer <- ''),
    let insert-item-after: &(FlexListKey) => Sync :=
        &(pivot) =>
            \ id := sync { gen-monotonic-id-string () },
            { insert (list, {after:pivot}, (id, { content: '', finished: No })) },
    { center [
        \ buffer := use { ui::State::[String] '' },
        { row [
            { ui::Input buffer },
            { ui::Button ('Add', { add-item-from buffer }) }
        ] },
        \ (id, index, item) := ui::ListView list,
        let content := (item proj |.(content)|),
        let finished := (item proj |.(finished)|),
        { row [
            { ui::Checkbox finished },
            { ui::Input content },
            { row [
                { SmallButton ('↑', (list move-up id)) }
                    . { with { ui::EnableCond { not (index is-first-in list) } } },
                { SmallButton ('↓', (list move-down id)) }
                    . { with { ui::EnableCond { not (index is-last-in list) } } },
                { SmallButton ('+', { insert-item-after id }) },
                { SmallButton ('×', (list delete id)) }
            ] }
        ] }
    ] };
